<?php

// 优惠券管理

namespace app\console\controller;

use think\Url;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Coupon as CouponModel;
use app\console\model\GoodsType as GoodsTypeModel;
use app\console\model\MemberCoupon as MemberCouponModel;
use think\Db;
class Coupon extends Controller
{

    /**
     * 优惠券列表
     * @param Request $request
     * @param CouponModel $coupon
     * @param GoodsTypeModel $goodsType
     * @return mixed
     */
    public function index(Request $request, CouponModel $coupon, GoodsTypeModel $goodsType,$pa=10)
    {
        // 获取参数
        $inquire = $request->instance()->param();

        // 搜索条件
        $condition['c.id'] = ['not in', '65'];
        if (!empty($inquire['title'])) $condition['c.title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['type'])) $condition['c.type'] = ['like', '%' . $inquire['type'] . '%'];
        if (!empty($inquire['single_id'])) $condition['c.single_id'] = ['like', '%' . $inquire['single_id'] . '%'];
        if (!empty($inquire['parenTid'])) $condition['c.parenTid'] = ['eq', $inquire['parenTid']];
        if (!empty($inquire['interval_timer'])) {
            $interval_timer = explode(' / ', $inquire['interval_timer']);
            $condition['c.create_time'] = ['between time', [($interval_timer[0]), ($interval_timer[1])]];
        }
        $data = $coupon->where($condition)
            ->alias('c')
            ->order(['id' => 'desc'])
            ->join('member m','c.member_id = m.id','left')
            ->field('c.*,m.username')
            ->paginate($pa,false,['query' => $inquire])->each(function($item,$key){
                if($item->type == 1){
                    $item->type = '商品优惠券';
                }
                if($item->type == 2){
                    $item->type = '服务优惠券';
                }
                $item->single_id = Db::name('single')->where('id',$item->single_id)->value('cat_name');
            });
        $single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->select();
        $single = getMenuTree($single);

        if(isset($inquire['export'])){

            $this->push_coupon($data->toArray()['data']);
        }
        return $this->fetch('index', [
            'mate_title' => '优惠券列表',
            'data'       => $data,
            'classify'   => $goodsType->where(['parenTid' => '0', 'status' => '1'])->select(),
            'single' => $single
        ]);
    }

    public function push_coupon($data,$name = '优惠券导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->getActiveSheet()->getColumnDimension(\PHPExcel_Cell::stringFromColumnIndex(0))->setAutoSize(true);
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '优惠券ID')
            ->setCellValue('B1', '优惠券分类')
            ->setCellValue('C1', '发放数量')
            ->setCellValue('D1', '服务分类')
            ->setCellValue('E1', '优惠券标题')
            ->setCellValue('F1', '使用价格')
            ->setCellValue('G1', '满减价格')
            ->setCellValue('H1', '开始时间 / 结束时间')
            ->setCellValue('I1', '创建时间');
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(30010);

        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['type'])
                ->setCellValue('C' . $num, $v['number'])
                ->setCellValue('D' . $num, $v['single_id'])
                ->setCellValue('E' . $num, $v['title'])
                ->setCellValue('F' . $num, $v['actual_price'])
                ->setCellValue('G' . $num, $v['virtual_price'])
                ->setCellValue('H' . $num, date('Y-m-d H:i:s',$v['start_time']).'-'.date('Y-m-d H:i:s',$v['end_time']))
                ->setCellValue('I' . $num, date('Y-m-d H:i:s',$v['create_time']));
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('优惠券导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * @param Request $request
     * @param CouponModel $coupon
     * @param GoodsTypeModel $goodsType
     * @return mixed注册用有会员
     */
    public function index2(Request $request, CouponModel $coupon, GoodsTypeModel $goodsType)
    {
        // 获取参数
        $inquire = $request->instance()->param();

        // 搜索条件
        $condition['c.id'] = ['in','65'];
        if (!empty($inquire['title'])) $condition['c.title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['parenTid'])) $condition['c.parenTid'] = ['eq', $inquire['parenTid']];
        $data = $coupon->where($condition)
            ->alias('c')
            ->order(['id' => 'desc'])
            ->join('member m','c.member_id = m.id','left')
            ->field('c.*,m.username')
            ->paginate(10);
        return $this->fetch('index2', [
            'mate_title' => '注册送优惠券',
            'data'       => $data,
            'classify'   => $goodsType->where(['parenTid' => '0', 'status' => '1'])->select()
        ]);
    }


    /**
     * 新增优惠券
     * @param Request $request
     * @param CouponModel $coupon
     * @param GoodsTypeModel $goodsType
     * @return mixed
     */
    public function create(Request $request, CouponModel $coupon, GoodsTypeModel $goodsType)
    {
        if ($request->instance()->isPost()) {


            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('Coupon');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            //if ($data['virtual_price']<$data['actual_price']) fail('满减金额必须大于优惠金额');

            //if ($data['virtual_price']==0||$data['actual_price']==0) fail('满减金额和优惠金额必须大于0！！！');

            // 提交数据
            $dispose = $coupon->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('Coupon/index'));
            }

            fail('操作失败');

        }

        $single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->select();
        $single = getMenuTree($single);
        return $this->fetch('create', [
            "mate_title" => '优惠券添加',
            'single_list' => $single,
            'data'       => $goodsType->where(['parenTid' => '0', 'status' => '1'])->select()
        ]);
    }


    /**
     * 编辑优惠券
     * @param $id
     * @param Request $request
     * @param CouponModel $coupon
     * @param GoodsTypeModel $goodsType
     * @return mixed
     */
    public function update($id, Request $request, CouponModel $coupon, GoodsTypeModel $goodsType)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            // 验证
            $validate = Loader::validate('Coupon');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $coupon->allowField(true)->save($data, ['id' => $id]);

            if ($dispose !== false) {
                win('操作成功', Url::build('Coupon/index'));
            }

            fail('操作失败');

        }

        $item = CouponModel::get($id);

        $single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->select();

        $single = getMenuTree($single);
        return $this->fetch('create', [
            "mate_title" => '优惠券编辑',
            'item'       => $item,
            'single_list' => $single,
            'data'       => $goodsType->where(['parenTid' => '0', 'status' => '1'])->select()

        ]);
    }


    /**
     * 删除优惠券
     * @param $id
     * @param CouponModel $coupon
     */
    public function destroy($id, CouponModel $coupon)
    {

        if ($coupon->destroy($id)) {

            win('操作成功', Url::build('Coupon/index'));
        }

        fail('操作失败');

    }


    /**
     * 更新优惠券状态
     * @param CouponModel $coupon
     * @return bool|int
     */
    public function auditing(CouponModel $coupon)
    {
        $id = Request::instance()->param('id');

        $status = $coupon->where(['id' => $id])->value('status') == '1' ? 2 : 1;

        if ($coupon->where(['id' => $id])->update(['status' => $status])) {
            return $status;
        }

        return false;
    }


    public function examine(MemberCouponModel $memberCoupon)
    {
        $id = Request::instance()->param('id');



    }
}